package chat

import (
	"im/model/request"
)

// 集中控制器对象
type Hub struct {
	// client 信息
	Clients map[uint]*Client
	// 在线用户Id
	// OnlineUserIds map[uint]bool
	// 广播信息channel
	Boardcast chan []byte
	// 上线信息channel
	Register chan *Client
	// 下线信息channel
	Unregister chan *Client
	// 私聊
	PrivateChat chan *request.MessageReq
	// 群聊
	GroupChat chan *request.MessageReq
}

// 初始化 hub 控制器
func CreateHub() *Hub {
	return &Hub{
		// Clients:       make(map[*Client]bool),
		Clients:     make(map[uint]*Client),
		Boardcast:   make(chan []byte),
		Register:    make(chan *Client),
		Unregister:  make(chan *Client),
		PrivateChat: make(chan *request.MessageReq),
		GroupChat:   make(chan *request.MessageReq),
	}
}

/**
func (h *Hub) Run() {
	for {
		select {
		case client := <-h.Register:
			// 用户上线
			h.Clients[client.UserId] = client
			fmt.Println("用户上线")
		case client := <-h.Unregister:
			// 用户下线
			// h.Clients[client] = false
			delete(h.Clients, client.UserId)
			fmt.Println("用户下线")
		case message := <-h.Boardcast:
			// 消息广播
			for _, client := range h.Clients {
				// 发送消息
				client.Send <- message
			}
		case messageReq := <-h.PrivateChat:
			// 私聊
			targetUserId := messageReq.TargeUserId
			fmt.Println("------私聊对象Id: ", targetUserId)
			if client := h.Clients[targetUserId]; client != nil {
				fmt.Println("------私聊对象: ", client)
				client.Send <- []byte(messageReq.Content)
			}
		case messageReq := <-h.GroupChat:
			// 群聊
			groupId := messageReq.GroupId
			fmt.Println("------群聊id: ", groupId)
			// 1. 在线：获取群成员信息
			cgms := service.AppService.ChatGroupMemberService
			if gms, err := cgms.GetGroupMembers(request.ChatGroupMemberReq{
				GroupId: groupId}); err != nil {
				// 获取群成员失败
			} else {
				// 2. 在线：给群成员发送消息
				for _, member := range gms {
					u := member.ID
					if client := h.Clients[u]; client != nil {
						client.Send <- []byte(messageReq.Content)
					}
				}
			}
		}
	}
}

*/
